import {
	apiMixUrlApi
} from '@/api/assemb.js';

function download(file, type) {
	let URl = file.audioUrl
	if (URl.indexOf('https') >= 0) {
		pchome(URl, file, type)
	} else {
		let prams = {
			files: [URl]
		};
		apiMixUrlApi(prams, 1003, 'uploadFileToOss').then(json => {
			let oss = result.ossUrl;
			pchome(oss[0], file, type)
		});
	}
}

function pchome(URl, file, type) {
	const downloadTask = uni.downloadFile({
		url: URl,
		success: (res) => {
			if (res.statusCode === 200) {
				uni.hideLoading();
				console.log('下载成功', res);
				switch (type) {
					case 'saveAlbum':
						saveAlbum(res)
						break;
					case 'exportToWeChat':
						exportToWeChat(res, file)
						break;
					default:
						break;
				}
			}
		},
		complete: () => {
			uni.hideLoading();
		}
	});
	downloadTask.onProgressUpdate((res) => {
		uni.showLoading({
			title: '下载' + res.progress + '%'
		});
		/* console.log('下载进度' + res.progress);
		console.log('已经下载的数据长度' + res.totalBytesWritten);
		console.log('预期需要下载的数据总长度' + res.totalBytesExpectedToWrite);
		// 满足测试条件，取消下载任务。
		if (res.progress > 50) {
			downloadTask.abort();
		} */
	});
}

function exportToWeChat(res, file) {
	console.log(res.tempFilePath, "导出至微信");
	let houzhui = file.audioUrl.match(/\.[^.]+?$/)[0];
	wx.shareFileMessage({
		filePath: res.tempFilePath,
		fileName: file.audioName + houzhui,
		success() {},
		fail: console.error
	});
}

function saveAlbum(res) {
	uni.saveVideoToPhotosAlbum({
		filePath: res.tempFilePath,
		success: function() {
			uni.showToast({
				title: '保存成功！',
				icon: 'success',
				duration: 2000
			});
		},
		fail: function() {
			uni.showToast({
				title: '保存失败！',
				icon: 'error',
				duration: 2000
			});
		}
	});
}


/*
 *保存文件到相册
 *@param - successc:成功回调
 *@param - failc:失败回调
 */
function saveVideoToPhotosAlbum(url) {
	uni.showLoading({
		title: '正在保存...'
	});
	//获取用户的当前设置。获取相册权限
	uni.getSetting({
		success: (res) => {
			//如果没有相册权限
			let permissions = ''
			// #ifdef MP-WEIXIN || MP-KUAISHOU
			permissions = "scope.writePhotosAlbum"
			if (!res.authSetting[permissions]) {
				//向用户发起授权请求
				uni.authorize({
					scope: permissions,
					success: () => {
						//授权成功保存图片到系统相册
						uni.saveVideoToPhotosAlbum({
							//图片路径，不支持网络图片路径
							filePath: url,
							success: (res) => {
								uni.hideLoading();
								return uni.showToast({
									title: "保存成功！",
								});
							},
							fail: (res) => {
								console.log(res.errMsg);
								return uni.showToast({
									title: res.errMsg,
								});
							},
							complete: (res) => {
								uni.hideLoading();
							},
						});
					},
					//授权失败
					fail: () => {
						uni.hideLoading();
						uni.showModal({
							title: "您已拒绝获取相册权限",
							content: "是否进入权限管理，调整授权？",
							success: (res) => {
								if (res.confirm) {
									//调起客户端小程序设置界面，返回用户设置的操作结果。（重新让用户授权）
									uni.openSetting({
										success: (res) => {
											console.log(res
											.authSetting);
										},
									});
								} else if (res.cancel) {
									return uni.showToast({
										title: "已取消！",
									});
								}
							},
						});
					},
				});
			} else {
				console.log(url, "url=========");
				//如果已有相册权限，直接保存图片到系统相册
				uni.saveVideoToPhotosAlbum({
					filePath: url,
					success: (res) => {
						uni.hideLoading();
						return uni.showToast({
							title: "保存成功！",
						});
					},
					fail: (res) => {
						uni.hideLoading();
						console.log(res.errMsg);
						return uni.showToast({
							title: res.errMsg,
						});
					},
					//无论成功失败都走的回调
					complete: (res) => {
						// uni.hideLoading();
					},
				});
			}
			// #endif
			// #ifdef MP-TOUTIAO
			//如果已有相册权限，直接保存图片到系统相册
			uni.saveVideoToPhotosAlbum({
				filePath: url,
				success: (res) => {
					uni.hideLoading();
					return uni.showToast({
						title: "保存成功！",
					});
				},
				fail: (res) => {
					uni.hideLoading();
					if (res.errNo == 10200) {
						uni.showToast({
							title: '请手动开启保存权限!',
						});
						tt.openSetting({
							success: res => {
								console.log('打开设置页面成功: ', res.errMsg);
							},
							fail: res => {
								console.log('打开设置页面失败: ', res.errMsg);
							},
							complete: res => {
								console.log('接口已调用: ', res.errMsg);
							}
						});
					} else {
						return uni.showToast({
							title: res.errMsg,
						});
					}
				},
				//无论成功失败都走的回调
				complete: (res) => {
					// uni.hideLoading();
				},
			});

			// #endif

		},
		fail: (res) => {},
	});
}

export {
	saveVideoToPhotosAlbum,
	download
}